package responses

import (
	"github.com/edgexfoundry/edgex-go/internal/app/dtos"
	common2 "github.com/edgexfoundry/edgex-go/internal/app/dtos/common"
	"github.com/edgexfoundry/edgex-go/internal/app/models"
	edgexDtos "github.com/edgexfoundry/go-mod-core-contracts/v2/dtos"
	"github.com/edgexfoundry/go-mod-core-contracts/v2/dtos/common"
)

type DeviceCommandResponse[T common2.PageEntity] struct {
	common.BaseResponse `json:",inline"`
	common2.PageInfo[T]
}

// NewDeviceCommandResponse device commands query
func NewDeviceCommandResponse(requestId string, message string, statusCode int, dcs []models.DeviceCommand, page, pageSize int, totalCount uint32) DeviceCommandResponse[dtos.DeviceCommand] {
	pageInfo := common2.NewPageInfo(page, pageSize, totalCount, ToDeviceCommandDTOs(dcs))
	return DeviceCommandResponse[dtos.DeviceCommand]{
		BaseResponse: common.NewBaseResponse(requestId, message, statusCode),
		PageInfo:     pageInfo,
	}
}

func ToDeviceCommandDTOs(drs []models.DeviceCommand) []dtos.DeviceCommand {
	deviceCommands := make([]dtos.DeviceCommand, len(drs))
	for index, dr := range drs {
		deviceCommands[index] = ToDeviceCommandDTO(dr)
	}
	return deviceCommands
}

func ToDeviceCommandDTO(d models.DeviceCommand) dtos.DeviceCommand {
	return dtos.DeviceCommand{
		DBTimestamp: edgexDtos.DBTimestamp{
			Created:  d.Created,
			Modified: d.Modified,
		},
		DeviceCommand:      edgexDtos.FromDeviceCommandModelToDTO(d.DeviceCommand),
		Code:               d.Code,
		Description:        d.Description,
		Id:                 d.Id,
		ResourceOperations: ToResourceOperationDTOs(d.ResourceOperations),
	}
}

func ToResourceOperationDTOs(ros []models.ResourceOperation) []dtos.ResourceOperation {
	operations := make([]dtos.ResourceOperation, len(ros))
	for index, dr := range ros {
		operations[index] = ToResourceOperationDTO(dr)
	}
	return operations
}

func ToResourceOperationDTO(d models.ResourceOperation) dtos.ResourceOperation {
	return dtos.ResourceOperation{
		ResourceOperation: edgexDtos.FromResourceOperationModelToDTO(d.ResourceOperation),
		UUID:              d.UUID,
		ResourceCode:      d.ResourceCode,
		Resource:          ToDeviceResourceDTO(d.Resource),
	}
}
